#![allow(unused_imports,dead_code,unused_assignments)]
use axum::{
    extract::{Form, Query, Json, Multipart,DefaultBodyLimit},
    routing::{get,post},
    response::Response,
    body::{Body, Bytes},
    Router
};
use crate::domain::UserBean;
use crate::domain::UserQueryRequest;
use crate::serviceimpl::role_service::find_role_by_role_name as service_find_role_by_role_name;
use crate::serviceimpl::user_service::activate_all_users as service_activate_all_users;
use crate::serviceimpl::user_service::activate_user as service_activate_user;
use crate::serviceimpl::user_service::add_user as service_add_user;
use crate::serviceimpl::user_service::assign_roles_to_user as service_assign_roles_to_user;
use crate::serviceimpl::user_service::change_password_user as service_change_password_user;
use crate::serviceimpl::user_service::clone_all_users as service_clone_all_users;
use crate::serviceimpl::user_service::clone_user as service_clone_user;
use crate::serviceimpl::user_service::count_search_users_by_fields_records as service_count_search_users_by_fields_records;
use crate::serviceimpl::user_service::delete_all_users as service_delete_all_users;
use crate::serviceimpl::user_service::delete_user as service_delete_user;
use crate::serviceimpl::user_service::find_user_by_id as service_find_user_by_id;
use crate::serviceimpl::user_service::find_user_by_user_name as service_find_user_by_user_name;
use crate::serviceimpl::user_service::find_user_shadow_by_user_name as service_find_user_shadow_by_user_name;
use crate::serviceimpl::user_service::list_active_user_roles_using_user_id as service_list_active_user_roles_using_user_id;
use crate::serviceimpl::user_service::list_active_users as service_list_active_users;
use crate::serviceimpl::user_service::list_all_users as service_list_all_users;
use crate::serviceimpl::user_service::list_available_active_user_roles_using_user_id as service_list_available_active_user_roles_using_user_id;
use crate::serviceimpl::user_service::register_user as service_register_user;
use crate::serviceimpl::user_service::revoke_roles_from_user as service_revoke_roles_from_user;
use crate::serviceimpl::user_service::search_users_by_fields as service_search_users_by_fields;
use crate::serviceimpl::user_service::search_users_by_fields_by_page as service_search_users_by_fields_by_page;
use crate::serviceimpl::user_service::soft_delete_all_users as service_soft_delete_all_users;
use crate::serviceimpl::user_service::soft_delete_user as service_soft_delete_user;
use crate::serviceimpl::user_service::toggle_one_user as service_toggle_one_user;
use crate::serviceimpl::user_service::toggle_user as service_toggle_user;
use crate::serviceimpl::user_service::update_user as service_update_user;
use crate::utils::excel_util::export_excel_workbook_with_image;
use crate::utils::pdf_util::export_pdf_with_images;
use serde::{Deserialize};
use serde_json::{Value,Map};
use std::collections::HashMap;
use std::fs;
use std::sync::Mutex;
use tower_http::{trace::TraceLayer};


lazy_static! {
	static ref TEMP_USER_IMAGES:Mutex<HashMap<String,String>> = Mutex::new(HashMap::new());
}

pub fn store_user_picture(key:String,photo:String) {
	TEMP_USER_IMAGES.lock().unwrap().insert(key,photo);
}

pub fn pick_user_picture(key:String) ->String {
	let ret:Option<String> = TEMP_USER_IMAGES.lock().unwrap().get(&key).cloned();
	TEMP_USER_IMAGES.lock().unwrap().insert(key,"".to_string());
	if ret.is_none() {
		return "".to_string();
	}
	ret.as_ref().unwrap().to_string()
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UserRequest {
	pub id: Option<i64>,
	pub user_name: Option<String>,
	pub active: Option<bool>,
	pub first_name: Option<String>,
	pub last_name: Option<String>,
	pub email: Option<String>,
	pub isadmin: Option<bool>,
	pub password: Option<String>,
	pub gender: Option<String>,
	pub salt: Option<String>,
	pub login_failure: Option<i32>,
	pub address: Option<String>,
	pub phone: Option<String>,
	pub description: Option<String>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IdsRequest {
	pub ids: String,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UserRoleMtmRequest {
	pub user_id: Option<i64>,
	pub role_ids:Option<String>,
}


pub fn user_controller() -> Router {
	Router::new()
	.route("/listAllUsers", post(list_all_users))
	.route("/updateUser", post(update_user))
	.route("/deleteUser", post(delete_user))
	.route("/addUser", post(add_user))
	.route("/softDeleteUser", post(soft_delete_user))
	.route("/findUserById", post(find_user_by_id))
	.route("/findUserByUserName", post(find_user_by_user_name))
	.route("/listActiveUsers", post(list_active_users))
	.route("/deleteAllUsers", post(delete_all_users))
	.route("/softDeleteAllUsers", post(soft_delete_all_users))
	.route("/toggleUser", post(toggle_user))
	.route("/toggleOneUser", post(toggle_one_user))
	.route("/searchUsersByFieldsByPage", post(search_users_by_fields_by_page))
	.route("/activateUser", post(activate_user))
	.route("/activateAllUsers", post(activate_all_users))
	.route("/exportUsers", get(export_users))
	.route("/exportUsersPDF", get(export_users_pdf))
	.route("/filterUsersExcel", get(filter_users_excel))
	.route("/filterUsersPDF", get(filter_users_pdf))
	.route("/cloneUser", post(clone_user))
	.route("/cloneAllUsers", post(clone_all_users))
	.route("/checkAccessUser", get(check_access_user))
	.route("/changePasswordUser", post(change_password_user))
	.route("/assignRolesToUser", post(assign_roles_to_user))
	.route("/revokeRolesFromUser", post(revoke_roles_from_user))
	.route("/listActiveUserRolesUsingUserId", post(list_active_user_roles_using_user_id))
	.route("/listAvailableActiveUserRolesUsingUserId", post(list_available_active_user_roles_using_user_id))
	.route("/addUploadUserPhoto", post(add_upload_user_photo))
	.layer(DefaultBodyLimit::max(2*1024*1024))
	.layer(TraceLayer::new_for_http())
}
pub async fn activate_all_users(Form(ids_request):Form<IdsRequest>) ->String {
	let ids = ids_request.ids;
	let string_ids:Vec<&str> = ids.split(',').collect();
	let mut ids:Vec<i64> = Vec::new();

	let vecter_iterator = string_ids.iter();
	for id in vecter_iterator {
		ids.push(id.parse::<i64>().unwrap());
	}

	let _result = service_activate_all_users(ids).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn activate_user(Form(user_request):Form<UserRequest>) ->String {
	let id = user_request.id.unwrap_or_default();
	let _result = service_activate_user(id).await;
	match _result {
		Err(_) => {
			println!("Error!");
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			//println!("{}", resultjson);
			return resultjson;
		}
	}
}

pub async fn add_upload_user_photo(mut multipart:Multipart) ->String {
		while let Some(field) = multipart.next_field().await.unwrap() {
			let name = field.name().unwrap().to_string();
			if name == "files[]" {
				let content_type = field.content_type().unwrap().to_string();
				if content_type.starts_with("image/") {
					let data = field.bytes().await.unwrap();
					let data_str = base64::encode(data);
					store_user_picture("photo".to_string(),data_str.clone());
					
					let mut map = Map::new();
					map.insert("success".to_string(), Value::from(true));
					map.insert(
						"rows".to_string(),
						Value::from(data_str.clone()),
					);
				
					let resultjson = serde_json::to_string_pretty(&map).unwrap();
					return resultjson;
				}
			}
		}
		r#"{  "rows": null,  "success": true}"#.to_string()
}

pub async fn add_user(Json(user_request):Json<UserRequest>) ->String {
	let id = user_request.id.unwrap_or_default();
	let user_name = user_request.user_name.unwrap_or_default();
	let active = user_request.active.unwrap_or_default();
	let first_name = user_request.first_name.unwrap_or_default();
	let last_name = user_request.last_name.unwrap_or_default();
	let email = user_request.email.unwrap_or_default();
	let isadmin = user_request.isadmin.unwrap_or_default();
	let password = user_request.password.unwrap_or_default();
	let gender = user_request.gender.unwrap_or_default();
	let salt = user_request.salt.unwrap_or_default();
	let login_failure = user_request.login_failure.unwrap_or_default();
	let address = user_request.address.unwrap_or_default();
	let phone = user_request.phone.unwrap_or_default();
	let description = user_request.description.unwrap_or_default();
	let my_photo = pick_user_picture("photo".to_string());

	let user = UserBean{
	id : id,
	user_name : user_name,
	active : active,
	first_name : first_name,
	last_name : last_name,
	email : email,
	isadmin : isadmin,
	password : password,
	gender : gender,
	salt : salt,
	login_failure : login_failure,
	address : address,
	phone : phone,
	description : description,
	photo : my_photo,
	};
	
	let user0 = service_find_user_by_user_name(user.clone().user_name).await;

	match user0 {
		Ok(user0) => {
			if user0.id > 0 {
				return r#"{  "rows": null,  "success": false, "error":"用户已存在"}"#.to_string();
			}
		},
		Err(_) => {
		}
	}
	let _result = service_add_user(user.clone()).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let role = service_find_role_by_role_name("user".to_string()).await.unwrap();
			let user = service_find_user_by_user_name(user.clone().user_name).await.unwrap();
			let _ = service_assign_roles_to_user(user.id,vec![role.id]).await;
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn assign_roles_to_user(Form(user_role_mtm_request):Form<UserRoleMtmRequest>) ->String {
	let user_id = user_role_mtm_request.user_id.unwrap_or_default();
	let role_ids_str = user_role_mtm_request.role_ids.unwrap_or_default();
	let string_ids:Vec<&str> = role_ids_str.split(',').collect();
	let mut role_ids:Vec<i64> = Vec::new();

	let vecter_iterator = string_ids.iter();
	for role_id in vecter_iterator {
		role_ids.push(role_id.parse::<i64>().unwrap());
	}

	let _result = service_assign_roles_to_user(user_id,role_ids).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn change_password_user(Form(user_request):Form<UserRequest>) ->String {
	let user_name = user_request.user_name.unwrap_or_default();
	let password = user_request.password.unwrap_or_default();
	let mut user = service_find_user_by_user_name(user_name).await.unwrap();
	user.password = password;
	let _result = service_change_password_user(user).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn check_access_user() ->String {
	r#"{  "rows": null,  "success": true}"#.to_string()
}

pub async fn clone_all_users(Form(ids_request):Form<IdsRequest>) ->String {
	let ids = ids_request.ids;
	let string_ids:Vec<&str> = ids.split(',').collect();
	let mut ids:Vec<i64> = Vec::new();

	let vecter_iterator = string_ids.iter();
	for id in vecter_iterator {
		ids.push(id.parse::<i64>().unwrap());
	}

	let _result = service_clone_all_users(ids).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn clone_user(Form(user_request):Form<UserRequest>) ->String {
	let id = user_request.id.unwrap_or_default();
	let _result = service_clone_user(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn delete_all_users(Form(ids_request):Form<IdsRequest>) ->String {
	let ids = ids_request.ids;
	let string_ids:Vec<&str> = ids.split(',').collect();
	let mut ids:Vec<i64> = Vec::new();

	let vecter_iterator = string_ids.iter();
	for id in vecter_iterator {
		ids.push(id.parse::<i64>().unwrap());
	}

	let _result = service_delete_all_users(ids).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn delete_user(Form(user_request):Form<UserRequest>) ->String {
	let id = user_request.id.unwrap_or_default();
	let _result = service_delete_user(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn export_users() ->Response<Body> {
	let list = service_list_all_users().await.unwrap();
	let mut contents : Vec<Vec<String>> = Vec::new();
	let sheet_name = "用户信息表".to_string();
	let headers = vec!["序号".to_string(),"用户名".to_string(),"活跃".to_string(),"名字".to_string(),"姓".to_string(),"电子邮件".to_string(),"是否管理员".to_string(),"性别".to_string(),"地址".to_string(),"电话".to_string(),"描述".to_string(),"照片".to_string()];
	let is_images = vec![false,false,false,false,false,false,false,false,false,false,false,true];
	for user in list {

		let row = vec![user.id.to_string(),user.user_name,user.active.to_string(),user.first_name,user.last_name,user.email,user.isadmin.to_string(),user.gender,user.address,user.phone,user.description,user.photo];
		contents.push(row);
	}

	let full_file_path = "./template/temp/users.xlsx";
	export_excel_workbook_with_image(full_file_path.to_string(),sheet_name, headers, contents, is_images);
	
	
	let data = fs::read(full_file_path).unwrap();
	let _ = fs::remove_file(full_file_path);

	Response::builder()
	.header("Content-Type", "application/octet-stream")
	.header("Content-Disposition", "attachment; filename=users.xlsx")
	.header("Content-Transfer-Encoding", "binary")
	.body(Body::from(data))
	.unwrap()
}

pub async fn export_users_pdf() ->Response<Body> {
	let list = service_list_all_users().await.unwrap();
	let mut contents : Vec<Vec<String>> = Vec::new();
	let sheet_name = "用户信息表".to_string();
	let headers = vec!["序号".to_string(),"用户名".to_string(),"活跃".to_string(),"名字".to_string(),"姓".to_string(),"电子邮件".to_string(),"是否管理员".to_string(),"性别".to_string(),"地址".to_string(),"电话".to_string(),"描述".to_string(),"照片".to_string()];
	let is_images = vec![false,false,false,false,false,false,false,false,false,false,false,true];
	for user in list {

		let row = vec![user.id.to_string(),user.user_name,user.active.to_string(),user.first_name,user.last_name,user.email,user.isadmin.to_string(),user.gender,user.address,user.phone,user.description,user.photo];
		contents.push(row);
	}

	let data = export_pdf_with_images(sheet_name, headers, contents, is_images);
	
	Response::builder()
	.header("Content-Type", "application/octet-stream")
	.header("Content-Disposition", "attachment; filename=users.pdf")
	.header("Content-Transfer-Encoding", "binary")
	.body(Body::from(data))
	.unwrap()
}

pub async fn filter_users_excel(Query(user_query_request):Query<UserQueryRequest>) ->Response<Body> {
	let list = service_search_users_by_fields(user_query_request).await.unwrap();
	let mut contents : Vec<Vec<String>> = Vec::new();
	let sheet_name = "用户信息表".to_string();
	let headers = vec!["序号".to_string(),"用户名".to_string(),"活跃".to_string(),"名字".to_string(),"姓".to_string(),"电子邮件".to_string(),"是否管理员".to_string(),"性别".to_string(),"地址".to_string(),"电话".to_string(),"描述".to_string(),"照片".to_string()];
	let is_images = vec![false,false,false,false,false,false,false,false,false,false,false,true];
	for user in list {

		let row = vec![user.id.to_string(),user.user_name,user.active.to_string(),user.first_name,user.last_name,user.email,user.isadmin.to_string(),user.gender,user.address,user.phone,user.description,user.photo];
		contents.push(row);
	}

	let full_file_path = "./template/temp/users.xlsx";
	export_excel_workbook_with_image(full_file_path.to_string(),sheet_name, headers, contents, is_images);
	
	
	let data = fs::read(full_file_path).unwrap();
	let _ = fs::remove_file(full_file_path);

	Response::builder()
	.header("Content-Type", "application/octet-stream")
	.header("Content-Disposition", "attachment; filename=users.xlsx")
	.header("Content-Transfer-Encoding", "binary")
	.body(Body::from(data))
	.unwrap()
}

pub async fn filter_users_pdf(Query(user_query_request):Query<UserQueryRequest>) ->Response<Body> {
	let list = service_search_users_by_fields(user_query_request).await.unwrap();
	let mut contents : Vec<Vec<String>> = Vec::new();
	let sheet_name = "用户信息表".to_string();
	let headers = vec!["序号".to_string(),"用户名".to_string(),"活跃".to_string(),"名字".to_string(),"姓".to_string(),"电子邮件".to_string(),"是否管理员".to_string(),"性别".to_string(),"地址".to_string(),"电话".to_string(),"描述".to_string(),"照片".to_string()];
	let is_images = vec![false,false,false,false,false,false,false,false,false,false,false,true];
	for user in list {

		let row = vec![user.id.to_string(),user.user_name,user.active.to_string(),user.first_name,user.last_name,user.email,user.isadmin.to_string(),user.gender,user.address,user.phone,user.description,user.photo];
		contents.push(row);
	}

	let data = export_pdf_with_images(sheet_name, headers, contents, is_images);

	Response::builder()
	.header("Content-Type", "application/octet-stream")
	.header("Content-Disposition", "attachment; filename=users.pdf")
	.header("Content-Transfer-Encoding", "binary")
	.body(Body::from(data))
	.unwrap()
}

pub async fn find_user_by_id(Form(user_request):Form<UserRequest>) ->String {
	let id = user_request.id.unwrap_or_default();
	let user = service_find_user_by_id(id).await;
	match user {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(user) => {
			let json = serde_json::to_string_pretty(&user).unwrap();

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);
		
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn find_user_by_user_name(Form(user_request):Form<UserRequest>) ->String {
	let user_name = user_request.user_name.unwrap_or_default();
	let user = service_find_user_by_user_name(user_name).await;
	match user {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(user) => {
			let json = serde_json::to_string_pretty(&user).unwrap();

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);
		
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn list_active_user_roles_using_user_id(Form(user_role_mtm_request):Form<UserRoleMtmRequest>) ->String {
	let user_id = user_role_mtm_request.user_id.unwrap_or_default();

	let roles = service_list_active_user_roles_using_user_id(user_id).await;
	match roles {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(roles) => {
			let json = serde_json::to_string_pretty(&roles).unwrap();

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);
		
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn list_active_users() ->String {
	let users = service_list_active_users().await;
	match users {
		Err(_) => {
			println!("Error!");
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(users) => {
			let json = serde_json::to_string_pretty(&users).unwrap();
			//println!("{}", json);

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);
		
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			//println!("{}", resultjson);
			return resultjson;
		}
	}
}

pub async fn list_all_users() ->String {
	let users = service_list_all_users().await;
	match users {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(users) => {
			let json = serde_json::to_string_pretty(&users).unwrap();

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);
		
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn list_available_active_user_roles_using_user_id(Form(user_role_mtm_request):Form<UserRoleMtmRequest>) ->String {
	let id = user_role_mtm_request.user_id.unwrap_or_default();

	let roles = service_list_available_active_user_roles_using_user_id(id).await;
	match roles {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(roles) => {
			let json = serde_json::to_string_pretty(&roles).unwrap();

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);
		
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn revoke_roles_from_user(Form(user_role_mtm_request):Form<UserRoleMtmRequest>) ->String {
	let user_id = user_role_mtm_request.user_id.unwrap_or_default();
	let role_ids_str = user_role_mtm_request.role_ids.unwrap_or_default();
	let string_ids:Vec<&str> = role_ids_str.split(',').collect();
	let mut role_ids:Vec<i64> = Vec::new();

	let vecter_iterator = string_ids.iter();
	for role_id in vecter_iterator {
		role_ids.push(role_id.parse::<i64>().unwrap());
	}

	let _result = service_revoke_roles_from_user(user_id,role_ids).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn search_users_by_fields_by_page(Form(user_query_request):Form<UserQueryRequest>) ->String {
	let users = service_search_users_by_fields_by_page(user_query_request.clone()).await;
	let total = service_count_search_users_by_fields_records(user_query_request.clone()).await.unwrap().count_num;
	match users {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(users) => {
			let json = serde_json::to_string_pretty(&users).unwrap();

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert("total".to_string(), Value::from(total));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);
		
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn soft_delete_all_users(Form(ids_request):Form<IdsRequest>) ->String {
	let ids = ids_request.ids;
	let string_ids:Vec<&str> = ids.split(',').collect();
	let mut ids:Vec<i64> = Vec::new();

	let vecter_iterator = string_ids.iter();
	for id in vecter_iterator {
		ids.push(id.parse::<i64>().unwrap());
	}

	let _result = service_soft_delete_all_users(ids).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn soft_delete_user(Form(user_request):Form<UserRequest>) ->String {
	let id = user_request.id.unwrap_or_default();
	let _result = service_soft_delete_user(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn toggle_one_user(Form(user_request):Form<UserRequest>) ->String {
	let id = user_request.id.unwrap_or_default();
	let _result = service_toggle_one_user(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn toggle_user(Form(user_request):Form<UserRequest>) ->String {
	let id = user_request.id.unwrap_or_default();
	let _result = service_toggle_user(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn update_user(Json(user_request):Json<UserRequest>) ->String {
	let id = user_request.id.unwrap_or_default();
	let user_name = user_request.user_name.unwrap_or_default();
	let active = user_request.active.unwrap_or_default();
	let first_name = user_request.first_name.unwrap_or_default();
	let last_name = user_request.last_name.unwrap_or_default();
	let email = user_request.email.unwrap_or_default();
	let isadmin = user_request.isadmin.unwrap_or_default();
	let gender = user_request.gender.unwrap_or_default();
	let address = user_request.address.unwrap_or_default();
	let phone = user_request.phone.unwrap_or_default();
	let description = user_request.description.unwrap_or_default();
	let old_user = service_find_user_by_id(id.clone()).await.unwrap();
	let ori_user = service_find_user_shadow_by_user_name(old_user.user_name.clone()).await.unwrap();
	let salt = ori_user.salt;
	let login_failure = ori_user.login_failure;
	let password = ori_user.password;
	let _current_user = service_find_user_by_id(id).await.unwrap();
	let current_photo = _current_user.photo;
	let mut my_photo = pick_user_picture("photo".to_string());
	if my_photo.len() == 0 && current_photo.len()>0 {
		my_photo = current_photo;
	}

	let user = UserBean{
	id : id,
	user_name : user_name,
	active : active,
	first_name : first_name,
	last_name : last_name,
	email : email,
	isadmin : isadmin,
	password : password,
	gender : gender,
	salt : salt,
	login_failure : login_failure,
	address : address,
	phone : phone,
	description : description,
	photo : my_photo,
	};
	
	let _result = service_update_user(user).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

